package com.chenbei.controller.admin;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.chenbei.common.annotation.LoginLog;
import com.chenbei.common.constants.CacheKeys;
import com.chenbei.common.enums.ResponseResultEnum;
import com.chenbei.common.service.ICaptchaService;
import com.chenbei.common.service.IEmailService;
import com.chenbei.common.util.ApiResponseUtil;
import com.chenbei.common.domain.vo.Captcha;
import com.chenbei.common.domain.vo.ApiResponse;
import com.chenbei.system.domain.SysUser;
import com.chenbei.system.service.ISysUserService;
import com.chenbei.common.domain.vo.AdminUserLogin;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

@Tag(name="用户管理")
@RestController("AdminLoginController")
@RequestMapping("/admin")
@Slf4j
public class LoginController {

    @Autowired
    private IEmailService qqEmailService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${captcha.expire}")
    private int captchaCodeExpire;

    @Qualifier("DefaultThreadPool")
    @Autowired
    private TaskExecutor defaultTaskExecutor;

    @Autowired
    private ISysUserService adminUserService;

    @Autowired
    private ICaptchaService captchaService;

    @Value("${app.key}")
    private String appKey;

    @Operation(summary = "登录")
    @PostMapping("login")
    @LoginLog
    public ApiResponse<Object> login(@RequestBody AdminUserLogin adminUserLogin) {
        //验证码验证
        String codeKey;
        if (adminUserLogin.getMode() == 1) {
            codeKey = adminUserLogin.getCaptchaKey();
        } else if (adminUserLogin.getMode() == 2){
            codeKey = adminUserLogin.getLoginName();
        } else {
            return ApiResponseUtil.fail(ResponseResultEnum.REQUEST_PARAM_VERIFY_FAILED, "非法的登陆方式");
        }
        String code = stringRedisTemplate.opsForValue().get(CacheKeys.VERIFICATION_CODE_CACHE_KEY + codeKey);
        if (code == null || !code.equals(adminUserLogin.getCode())) {
            return ApiResponseUtil.fail(ResponseResultEnum.REQUEST_PARAM_VERIFY_FAILED, "验证码错误");
        }

        stringRedisTemplate.delete(CacheKeys.VERIFICATION_CODE_CACHE_KEY + codeKey);
        SysUser sysUser = adminUserService.getByLoginName(adminUserLogin.getLoginName());
        if (sysUser == null) {
            return ApiResponseUtil.fail(ResponseResultEnum.USER_AUTHENTICATION_FAILED, "用户不存在");
        }

        if (adminUserLogin.getMode() == 1) {
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, appKey.getBytes());
            String password = aes.decryptStr(sysUser.getPassword());
            if (!password.equals(adminUserLogin.getPassword())) {
                return ApiResponseUtil.fail(ResponseResultEnum.USER_AUTHENTICATION_FAILED, "账号或密码不正确");
            }
        }

        if (sysUser.getStatus() != 1) {
            return ApiResponseUtil.fail(ResponseResultEnum.USER_AUTHENTICATION_FAILED, "用户已被禁用");
        }

        //设置相关登录后的数据
        StpUtil.login(sysUser.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return ApiResponseUtil.success(tokenInfo);
    }

    @Operation(summary = "获取验证码")
    @GetMapping("getCaptcha")
    public ApiResponse<Captcha> getCaptcha() {
        Captcha captcha1 = new Captcha();

        String key = IdUtil.fastUUID();
        AbstractCaptcha captcha = captchaService.generate(key);
        String imageBase64 = captcha.getImageBase64();

        captcha1.setKey(key);
        captcha1.setContent("data:image/png;base64," + imageBase64);

        return ApiResponseUtil.success(captcha1);
    }

    @Operation(summary = "发送邮箱验证码")
    @PostMapping("sendEmailCode")
    public ApiResponse<Object> sendEmailCode(String email) {
        if(!Validator.isEmail(email)) {
            return ApiResponseUtil.fail(ResponseResultEnum.REQUEST_PARAM_VERIFY_FAILED,"邮箱格式错误");
        }
        String captchaCode = RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set(CacheKeys.VERIFICATION_CODE_CACHE_KEY + email, captchaCode, captchaCodeExpire, TimeUnit.SECONDS);
        defaultTaskExecutor.execute(() -> {
            qqEmailService.sendText(email, "琛贝-验证码", "【琛贝】验证码" + captchaCode + "，请在" + captchaCodeExpire/60 + "分钟内完成验证。");
        });
        return ApiResponseUtil.success();
    }

    @Operation(summary = "发送短信验证码")
    @PostMapping("sendSmsCode")
    public ApiResponse<Object> sendSmsCode(String phone) {
        if (!Validator.isMobile(phone)) {
            return ApiResponseUtil.fail(ResponseResultEnum.REQUEST_PARAM_VERIFY_FAILED, "手机号格式错误");
        }
        return ApiResponseUtil.fail(ResponseResultEnum.SERVER_ERROR, "暂不支持发送手机验证码");
    }
}
